package com.example.gateway;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 角色判断是否为管理员
 */

@Component
public class RuleFilter implements GlobalFilter, Ordered {
    public RuleFilter() {
        super();
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path=exchange.getRequest().getURI().getPath();
        ServerHttpRequest request=exchange.getRequest();
        ServerHttpResponse response=exchange.getResponse();
        //对于分类添加和删除只有管理员才操作
        if(path.contains("category/add")||path.contains("category/del")){
            List<String> mannagers=response.getHeaders().get("manager");
           if(mannagers==null||Integer.parseInt(mannagers.get(0))!=1){
               response.setStatusCode(HttpStatus.UNAUTHORIZED);
               return response.setComplete();
           }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 2;
    }
}
